package com.tiger.userClient.http.apps;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.db.entity.*;
import com.tiger.userClient.Db;
import com.tiger.userClient.http.apps.type.AppCategoryRes;
import com.tiger.userClient.http.auth.type.UserRoleType;
import com.tiger.utils.ResponseUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/apps")
public class AppController {
    private final Db db;
    private final AppService appService;

    public AppController(Db db, AppService appService) {
        this.db = db;
        this.appService = appService;
    }

    //获取可用的服务分类
    @GetMapping("category")
    public Object category(@RequestAttribute(value = "isAuth", required = false) boolean isAuth, @RequestAttribute(value = "userId", required = false) Long userId, @RequestAttribute(value = "role", required = false) String role) {
//        LambdaQueryWrapper<AppCategory> wrap = new LambdaQueryWrapper<>();
//
//        List<AppCategory> rows;
//
//        if(isAuth) {
//            List<DictionaryItem> items = db.dictionaryItem.getItemsByCategory("PORTAL_USER_TYPE");
//
//            Optional<DictionaryItem> item = items.stream() // 将List转换为流
//                    .filter(v -> Objects.equals(v.getCode(), role)).findFirst();
//
//            Long[] relateds = {item.get().getId()};
//
//            rows = db.appCategory.selectAvailableCategoryByRelateds(relateds); //获取有权限的最顶级的分类
//
//
//        }else {
//            rows = db.appCategory.list(new LambdaQueryWrapper<AppCategory>().select(AppCategory::getId, AppCategory::getName, AppCategory::getParentId, AppCategory::isAuth).eq(AppCategory::isAuth, false).eq(AppCategory::getTopId, 0).eq(AppCategory::isEnable, true).orderByDesc(AppCategory::getSort, AppCategory::getId));
//        }
//
//        //获取最顶部的分类下面的所有分类
//        List<Integer> topIds = rows.stream().map(AppCategory::getId).collect(Collectors.toList());
//        List<AppCategory> subRows = db.appCategory.list(new LambdaQueryWrapper<AppCategory>().in(AppCategory::getTopId, topIds).orderByDesc(AppCategory::getSort, AppCategory::getId));
//        if(!subRows.isEmpty()) {
//            rows.addAll(subRows);
//        }
//
//
//
//        List<AppCategoryRes> list = new ArrayList<>();
//        for(AppCategory row : rows) {
//            List<Integer> ids = new ArrayList<>();
//            appService.querySubCategory(rows, ids, row.getId());
//            ids.add(row.getId());
//
//            AppCategoryRes appCategoryRes = new AppCategoryRes();
//            BeanUtils.copyProperties(row, appCategoryRes);
//            appCategoryRes.setAppCount(db.app.count(new LambdaQueryWrapper<App>().in(App::getCategory, ids)));
//
//
//            if(isAuth && row.getParentId() == 0) {
//                String id = appService.existsHistory(userId, row.getId());
//                if(id != null) {
//                    appCategoryRes.setHistoryId(id);
//                }
//            }
//
//            list.add(appCategoryRes);
//        }

        return ResponseUtil.successRes(appService.ableCategory(isAuth, userId, role));
    }

    //查询推荐的应用
    @GetMapping("history/{id}")
    public Object historys(@PathVariable String id, @RequestAttribute(value = "userId", required = true) Long userId) {
        return ResponseUtil.successRes(appService.historyApps(id));
    }

    //根据分类查询出应用
    @GetMapping("list/{id}")
    public Object list(@PathVariable Integer id) {
        AppCategory category = db.appCategory.getOne(new LambdaQueryWrapper<AppCategory>().select(AppCategory::getParentId, AppCategory::getTopId).eq(AppCategory::getId, id));
        if(category == null) return ResponseUtil.successRes();

        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(App::getSort, App::getId);
        wrapper.eq(App::getEnable, true);

        List<AppCategory> categories = db.appCategory.list(new LambdaQueryWrapper<AppCategory>().select(AppCategory::getId, AppCategory::getParentId).eq(AppCategory::getTopId, category.getTopId() == 0 ? id : category.getTopId()));
        List<Integer> subIds = new ArrayList<>();
        appService.querySubCategory(categories, subIds, id);

        if(subIds.isEmpty()) {
            wrapper.eq(App::getCategory, id);
        }else {
            subIds.add(id);
            wrapper.in(App::getCategory, subIds);
        }

        return ResponseUtil.successRes(db.app.list(wrapper));

    }


    //首页推荐的服务
    @GetMapping("recommend")
    public Object recommendApps(@RequestParam(name = "size", required = false, defaultValue = "4") int size, @RequestAttribute(value = "isAuth", required = false) boolean isAuth, @RequestAttribute(value = "role", required = false) String role) {

        List<Integer> ids = new ArrayList<>();


        if(isAuth) {
            List<DictionaryItem> items = db.dictionaryItem.getItemsByCategory("PORTAL_USER_TYPE");

            Optional<DictionaryItem> item = items.stream() // 将List转换为流
                    .filter(v -> Objects.equals(v.getCode(), role)).findFirst();


            Long[] relateds = {item.get().getId()};

            List<AppCategory> categories = db.appCategory.selectCategoryByRelateds(relateds);

            if(!categories.isEmpty()) {
                ids = categories.stream().map(AppCategory::getId).collect(Collectors.toList());
            }


            System.out.println(ids);

        }else { //没有登录的，就获取公共的
            LambdaQueryWrapper<AppCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(AppCategory::getId);
            wrapper.eq(AppCategory::isAuth, false);
            wrapper.eq(AppCategory::isEnable, true);
            wrapper.eq(AppCategory::getTopId, 0);
            List<AppCategory> categories = db.appCategory.list(wrapper);

            if(!categories.isEmpty()) {
                ids = categories.stream().map(AppCategory::getId).collect(Collectors.toList());
            }
        }

        if(!ids.isEmpty()) {
            LambdaQueryWrapper<AppCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(AppCategory::getId);
            wrapper.eq(AppCategory::isEnable, true);
            wrapper.in(AppCategory::getTopId, ids);
            List<AppCategory> categories = db.appCategory.list(wrapper);

            if(!categories.isEmpty()) {
                for(AppCategory c : categories) {
                    ids.add(c.getId());
                }
            }
        }



        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<>();
        //wrapper.select(App::getId, App::getCover, App::getCoverType, App::getBccolor, App::getName, App::getUrl);
        wrapper.eq(App::getEnable, true).in(App::getCategory, ids).eq(App::getRecommend, true);

        wrapper.orderByDesc(App::getSort);
        wrapper.orderByDesc(App::getVisitTimes);
        wrapper.orderByDesc(App::getId);
        wrapper.last("limit " + size);

        List<App> apps = db.app.list(wrapper);


        return ResponseUtil.successRes(apps);
    }


    //首页推荐的服务
    @GetMapping("home")
    public Object homeApps(@RequestParam(name = "size", required = false, defaultValue = "4") int size, @RequestAttribute(value = "isAuth", required = false) boolean isAuth, @RequestAttribute(value = "role", required = false) String role) {

        List<Integer> ids = new ArrayList<>();

        System.out.println("---------------hyome");
        System.out.println(isAuth);

        if(isAuth) {
            List<DictionaryItem> items = db.dictionaryItem.getItemsByCategory("PORTAL_USER_TYPE");

            System.out.println(items);

            Optional<DictionaryItem> item = items.stream() // 将List转换为流
                    .filter(v -> Objects.equals(v.getCode(), role)).findFirst();


            Long[] relateds = {item.get().getId()};

            System.out.println(relateds);

            List<AppCategory> categories = db.appCategory.selectCategoryByRelateds(relateds);

            System.out.println(categories);

            if(!categories.isEmpty()) {
                ids = categories.stream().map(AppCategory::getId).collect(Collectors.toList());
            }

        }else { //没有登录的，就获取公共的
            LambdaQueryWrapper<AppCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(AppCategory::getId);
            wrapper.eq(AppCategory::isAuth, false);
            wrapper.eq(AppCategory::isEnable, true);
            wrapper.eq(AppCategory::getTopId, 0);
            List<AppCategory> categories = db.appCategory.list(wrapper);

            if(!categories.isEmpty()) {
                ids = categories.stream().map(AppCategory::getId).collect(Collectors.toList());
            }
        }

        if(!ids.isEmpty()) {
            LambdaQueryWrapper<AppCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(AppCategory::getId);
            wrapper.eq(AppCategory::isEnable, true);
            wrapper.in(AppCategory::getTopId, ids);
            List<AppCategory> categories = db.appCategory.list(wrapper);

            if(!categories.isEmpty()) {
                for(AppCategory c : categories) {
                    ids.add(c.getId());
                }
            }
        }


        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<>();
        //wrapper.select(App::getId, App::getCover, App::getCoverType, App::getBccolor, App::getName, App::getUrl);
        wrapper.eq(App::getEnable, true).in(App::getCategory, ids);

        wrapper.orderByDesc(App::getVisitTimes);
        wrapper.orderByDesc(App::getId);
        wrapper.last("limit " + size);

        List<App> apps = db.app.list(wrapper);


        return ResponseUtil.successRes(apps);
    }

    @GetMapping("search")
    public Object search(@RequestParam(name = "key", required = false) String key, @RequestParam(name = "size", required = false, defaultValue = "10") String size, @RequestAttribute(value = "userId", required = true) Long userId, @RequestAttribute(value = "isAuth", required = false) boolean isAuth, @RequestAttribute(value = "role", required = false) String role) {
        List<App> apps = new ArrayList<>();

        if(key != null && !key.isEmpty()) {
            List<AppCategoryRes> cates = appService.ableCategory(isAuth, userId, role);
            List<Integer> ids = new ArrayList<>();
            cates.forEach(c -> ids.add(c.getId()));

            LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper();
            //wrapper.select(App::getId, App::getName, App::getCategory, App::getCover, App::getUrl, App::getCoverType);
            wrapper.eq(App::getEnable, true);

            if(!ids.isEmpty()) {
                wrapper.in(App::getCategory, ids);
            }

            wrapper.like(App::getName, key);
            wrapper.last("limit " + size);




            apps = db.app.list(wrapper);
        }

        return ResponseUtil.successRes(apps);

    }


    @PostMapping("visit/{id}")
    public void visit(@PathVariable("id") Long id, @RequestAttribute(value = "isAuth", required = false) boolean isAuth, @RequestAttribute(value = "userId", required = false) Long userId, @RequestAttribute(value = "userKey", required = false) String userKey) {
        if(isAuth) {
            appService.addHistory(id, userId, userKey);
        }
        appService.statistics(isAuth, id, userId);
    }
}
